//
//  ZMPayManager.swift
//  TravelForUser
//
//  Created by Rowling on 2020/9/21.
//  Copyright © 2020 智蚂优服. All rights reserved.
//

import UIKit

class ZMPayManager {
    // 支付渠道枚举
    enum PayMethod {
        case aliPay
        case wechatPay
    }
    // 暂时不用
    var payMethods = [PayMethod]()
    
    static let shard = ZMPayManager()
    
    private init(){
        bind()
    }
    
    var payCallBack = PublishSubject<ZMPayOption>()
    
    var disposeBag = DisposeBag()
    /// 当前在支付的订单编号
    var currentPayOrderNo = ""
    
    public func aliPayWithInfo(_ payInfo : String, orderNum : String) {
        currentPayOrderNo = orderNum
        AlipaySDK.defaultService()?.payOrder(payInfo, fromScheme: AliScheme, callback: { (_) in

        })
    }
    
    func wechatPay(_ data : [String : Any], orderNum : String) {
        currentPayOrderNo = orderNum
        if  let package = JSON(data)["jsConfig"]["packages"].string,
            let timestamp = JSON(data)["jsConfig"]["timeStamp"].string,
            let sign = JSON(data)["jsConfig"]["paySign"].string,
            let prepayid = JSON(data)["jsConfig"]["prepayid"].string,
            let partnerid = JSON(data)["jsConfig"]["partnerid"].string,
            let nonceStr = JSON(data)["jsConfig"]["nonceStr"].string {
            let req = PayReq()
            req.partnerId = partnerid
            req.prepayId = prepayid
            req.package = package
            req.nonceStr  = nonceStr
            req.timeStamp = UInt32(timestamp) ?? 0
            req.sign = sign
            WXApi.send(req) { (_) in

            }
        } else {
            ZMToast.showToast(title: "支付参数异常")
        }
    }
    
    func bind() {
        ZMNotification.shard.subject.filter { (op) -> Bool in
           switch op {
               case .payOtion(_):return true
               default:return false
           }
        }.subscribe { [unowned self] (e) in
            guard let op = e.element else {return}
            switch op {
                case .payOtion(let a):
                    self.payCallBack.onNext(a)
                default:
                    break
            }
            self.currentPayOrderNo = ""
        }.disposed(by: disposeBag)
    }

    func showPay(money : String, orderNo : String, api : ZMApiProvider, _ complete : @escaping (_ balanceOk : Bool, _ resp : [String : Any]) -> ()) {
        let v = ZMUtil.loadNibViewFullScreen(nibName: OrderChoosePayView.self)
        v.price.text = money
        v.payMoney = Double(money) ?? 0
        v.onPayCallback = { [weak self, weak v] type in
            guard let v = v, let self = self else {return}
            var payType = ""
            switch type {
                case .alipay:
                    payType = "alipay"
                    break;
                case .wechat:
                    payType = "weixin"
                    break;
                case .balancePay:
                    payType = "yue"
                case .ckPay:
                    payType = "mallYue"
                case .integral:
                    payType = "integral"
            }
            ZMToast.showActivity()
            api.rxRequest(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
                ZMToast.hiddenActivity()
                v.removeFromSuperview()
                if payType == "yue" || payType == "mallYue" {
                    complete(true, resp)
                } else {
                    let payStr = JSON(resp)["alipayRequest"].stringValue
                    if payType == "weixin" {
                        ZMPayManager.shard.wechatPay(resp, orderNum: orderNo)
                    } else {
                        ZMPayManager.shard.aliPayWithInfo(payStr, orderNum: orderNo)
                    }
                    complete(false, resp)
                }
            }).disposed(by: self.disposeBag)
        }
        APPWindow?.addSubview(v)
    }
}
